03. Creating an Array

Arrays

An array is useful because it stores multiple values into a single, organized data structure. You can define a new array by listing values separated with commas between square brackets [].

// creates a `donuts` array with three strings
var donuts = ["glazed", "powdered", "jelly"];

But strings aren’t the only type of data you can store in an array. You can also store numbers, booleans… and really anything!

// creates a `mixedData` array with mixed data types
var mixedData = ["abcd", 1, true, undefined, null, "all the things"];

You can even store an array in an array to create a nested array!

// creates a `arraysInArrays` array with three arrays
var arraysInArrays = [[1, 2, 3], ["Julia", "James"], [true, false, true, false]];

Nested arrays can be particularly hard to read, so it's common to write them on one line, using a newline after each comma:

var arraysInArrays = [
  [1, 2, 3], 
  ["Julia", "James"], 
  [true, false, true, false]
];

Later in this lesson, we’ll look into some unique situations where nested arrays can be useful.

Mismatched Arrays

Select the valid arrays from the list below.

SOLUTION:
  • [33, 91, 13, 9, 23]
  • [null, "", undefined, []]
  • [3.14, "pi", 3, 1, 4, "Yum, I like pie!"]